﻿using UnityEngine;
using System.Collections;

///<summary>
/// Projectile that follow it's target until contact or leaving it's range of action
///</summary>
public class MissileBehaviour : Projectile {

    private Transform target;
	
	// Update is called once per frame
	void Update () 
    {
        //move the missile forward (local)
        rigidbody.transform.Translate(Vector3.forward * Time.deltaTime * speed);
        //If the missile left the range of effect, it is destroyed
        if(Vector3.Distance(transform.position, startPosition) > range)
        {
            explode();
        }

        //Force the missile to face it's target so it move towards it when translating forward
        //It explodes if the target disapeared
        if (target)
        {
            transform.LookAt(target);
        }
        else
        {
            explode();
        }
	}

    void OnTriggerEnter(Collider collider)
    {
        //Collides with air ennemies only, it then applies damages and explodes
        if (collider.gameObject.tag == "Ennemy_air")
        {
            if (collider.GetComponent<EnnemyBehaviour>())
            {
                collider.GetComponent<EnnemyBehaviour>().applyDamages(damage);
            }
            Destroy(gameObject);
        }
    }

    private void explode()
    {
        Destroy(gameObject);
    }

    public void setTarget(Transform newTarget)
    {
        target = newTarget;
    }
}
